package vip.idiy.anwei_android_iot;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.commons.lang3.StringUtils;

import java.util.List;

import vip.idiy.anwei_android_iot.domin.DeviceData;
import vip.idiy.anwei_android_iot.utils.ActivityFactory;
import vip.idiy.anwei_android_iot.utils.DatabaseUtil;
import vip.idiy.anwei_android_iot.utils.IotUtil;
import vip.idiy.anwei_android_iot.utils.ViewUtil;
import vip.idiy.anwei_android_iot.utils.dbHandle.DeviceDataHandle;
import vip.idiy.anwei_android_iot.views.LayoutTableRow;

/**
 * 设备管理
 */
public class DeviceHandleActivity extends AppCompatActivity {
    private final String TAG = "myTag " + " DeviceHandleActivity ";

    private DeviceDataHandle deviceDataHandle;
    // 默认页码
    private final int DEFAULT_PAGE = 1;
    // 总页码
    private int totalPages;
    private TextView layout_reuse_table_total_text_view;
    // 当前页码
    private int now_page;
    // 当前页码内容
    private EditText layout_reuse_table_page_edit_text;

    private TableLayout tableLayout;

    // 查询编辑框内容
    private EditText layout_reuse_table_query_content_edit_text;

    // 查询参数
    private final String QUERY_DEVICE_ID = "device_id";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_handle);
        // 设置设透明状态栏,导航栏. 状态栏字体修改为黑色
        ViewUtil.setViewStyle(this, true);

        ActivityFactory.setDeviceHandleActivity(this);

        // 初始化窗口
        initView();
        // 初始化数据
        initData();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        DatabaseUtil databaseUtil = DatabaseUtil.getInstance(this);
        deviceDataHandle = new DeviceDataHandle(databaseUtil);
        // 设置默页码
        layout_reuse_table_page_edit_text.setText(String.valueOf(DEFAULT_PAGE));
        // 获取数据列表
        getList(null, null, DEFAULT_PAGE);
    }

    /**
     * 初始化窗口
     */
    private void initView() {
        // 标题
        TextView layout_reuse_head_tv_title = findViewById(R.id.layout_reuse_head_tv_title);
        layout_reuse_head_tv_title.setText(R.string.page_device_handle);
        // 表格
        tableLayout = findViewById(R.id.table_layout);
        // 查询标题
        TextView layout_reuse_table_query_text_view = findViewById(R.id.layout_reuse_table_query_text_view);
        layout_reuse_table_query_text_view.setText(R.string.table_device_id);
        // 查询内容
        layout_reuse_table_query_content_edit_text = findViewById(R.id.layout_reuse_table_query_content_edit_text);
        // 总页码
        layout_reuse_table_total_text_view = findViewById(R.id.layout_reuse_table_total_text_view);
        // 当前页码
        layout_reuse_table_page_edit_text = findViewById(R.id.layout_reuse_table_page_edit_text);
        // 返回按钮
        findViewById(R.id.layout_reuse_head_return_myImageButton).setOnClickListener(v -> finish());
        // 添加按钮
        findViewById(R.id.layout_reuse_table_add_myImageButton)
                .setOnClickListener(v -> goToDeviceDataHandle(GlobalApplication.ADD_MODE, null));
        // 刷新
        findViewById(R.id.layout_reuse_table_flush_myImageButton)
                .setOnClickListener(v -> getList(null, null, now_page));
        // 查询
        findViewById(R.id.layout_reuse_table_query_myImageButton).setOnClickListener(v -> {
            String par = layout_reuse_table_query_content_edit_text.getText().toString().trim();
            if (StringUtils.isEmpty(par)) {
                getList(null, null, DEFAULT_PAGE);
            } else {
                getList(new String[]{QUERY_DEVICE_ID}, new String[]{par}, DEFAULT_PAGE);
            }
        });
        // 上一页
        findViewById(R.id.layout_reuse_table_prev_page).setOnClickListener(v -> {
            String page = layout_reuse_table_page_edit_text.getText().toString().trim();
            getList(null, null, StringUtils.isEmpty(page) ? DEFAULT_PAGE : Integer.parseInt(page) - 1);
        });
        // 下一页
        findViewById(R.id.layout_reuse_table_next_page).setOnClickListener(v -> {
            String page = layout_reuse_table_page_edit_text.getText().toString().trim();
            getList(null, null, StringUtils.isEmpty(page) ? DEFAULT_PAGE : Integer.parseInt(page) + 1);
        });

    }

    /**
     * 获取数据列表
     *
     * @param columnNames
     * @param columnValues
     * @param page
     */
    private void getList(String[] columnNames, String[] columnValues, int page) {
        Log.i(TAG, "getList: ");

        // 清空
        tableLayout.removeAllViews();
        // 添加表头
        boolean[] tableIsShow = {true, true, true, true, false, false, true};
        // 表头不需要按钮
        LayoutTableRow tableRow = new LayoutTableRow(this).init(tableIsShow, false, false)
                .setData(0, getString(R.string.table_device_id))
                .setTextColor(0, getColor(R.color.white))
                .setData(1, getString(R.string.table_wifi_name))
                .setTextColor(1, getColor(R.color.white))
                .setData(2, getString(R.string.table_mqtt_server))
                .setTextColor(2, getColor(R.color.white))
                .setData(3, getString(R.string.table_mqtt_name))
                .setTextColor(3, getColor(R.color.white))
                .setData(6, getString(R.string.table_handle))
                .setTextColor(6, getColor(R.color.white))
                .setBackground(R.drawable.ripple_blue);
        tableLayout.addView(tableRow);

        int count = deviceDataHandle.getTotalRecordCount(columnValues);
        if (count == 0) {
            layout_reuse_table_total_text_view.setText(String.format(getResources().getString(R.string.data_total), 0));
            Toast.makeText(this, R.string.error_data_is_null, Toast.LENGTH_SHORT).show();
            return;
        }
        // 获取页码
        totalPages = IotUtil.getTotalPages(count);
        if (page > totalPages) {
            Toast.makeText(this, R.string.error_page_is_max, Toast.LENGTH_SHORT).show();
            return;
        }
        if (page == 0) {
            Toast.makeText(this, R.string.error_page_is_min, Toast.LENGTH_SHORT).show();
            return;
        }
        now_page = page;
        // 设置显示当前页码
        layout_reuse_table_page_edit_text.setText(String.valueOf(page));
        // 设置显示页码
        layout_reuse_table_total_text_view.setText(String.format(getResources().getString(R.string.data_total), totalPages));
        // 获取列表
        List<DeviceData> deviceDataList = deviceDataHandle.getList(columnNames, columnValues, page);
        // 设置显示的列  7列,只显示一列
        boolean[] isShow = {true, true, true, true, false, false, true};
        for (DeviceData deviceData : deviceDataList) {
            LayoutTableRow layoutTableRow = new LayoutTableRow(this).init(isShow, false, true)
                    .setData(0, deviceData.getDeviceId()) // 设备ID
                    .setData(1, deviceData.getWifiName()) // wifi名称
                    .setData(2, deviceData.getMqttServer()) // mqtt服务器
                    .setData(3, deviceData.getMqttName()) // mqtt账号
                    .setEditAndRemovePar(deviceData.getDeviceId()) // 设置编辑和删除需要的参数
                    .setEditButtonClickListener(text -> goToDeviceDataHandle(GlobalApplication.EDIT_MODE, text)) // 编辑
                    .setRemoveButtonClickListener(text -> goToDeviceDataHandle(GlobalApplication.REMOVE_MODE, text)); // 移除
            tableLayout.addView(layoutTableRow);
        }
    }

    /**
     * 跳转AddEditInfoActivity
     *
     * @param mode
     * @param device_id
     */
    private void goToDeviceDataHandle(int mode, String device_id) {
        Intent intent = new Intent(this, AddEditDataActivity.class);
        intent.putExtra("mode", mode);
        intent.putExtra("par", device_id);
        startActivity(intent);
    }

    public void flushList(int mode) {
        int page = now_page;
        switch (mode) {
            case GlobalApplication.EDIT_MODE:
                getList(null, null, page);
                break;
            case GlobalApplication.ADD_MODE:
                page = IotUtil.getTotalPages(deviceDataHandle.getTotalRecordCount(null));
                getList(null, null, page);
                break;
            case GlobalApplication.REMOVE_MODE:
                int totalPage = IotUtil.getTotalPages(deviceDataHandle.getTotalRecordCount(null));
                page = Math.min(totalPage, now_page);
                getList(null, null, page);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityFactory.mainActivity_defaultSelectHome();
    }
}